//
//  ProjectModifyTableViewController.swift
//  XMGG
//
//  Created by iDev on 6/26/17.
//  Copyright © 2017 iDev. All rights reserved.
//

import UIKit
import SVProgressHUD
import Alamofire
import SwiftyJSON

class ModifyProjectViewController: UIViewController,UIGestureRecognizerDelegate,ModifyProjectViewDelegate {

    var projectView:ModifyProjectView?
    var modle:ModifyProjectModle?
    var mode:ProjectMode?
    
    private var oldNavDelegate:UIGestureRecognizerDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        projectView = ModifyProjectView(frame: UIScreen.main.bounds, modle:modle!, mode:mode!)
        view.addSubview(projectView!)
        projectView?.delegate = self
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        projectView?.modle = modle
        projectView?.reloadData()
//        private var oldNavDelegate:UIGestureRecognizerDelegate?
        let backBarBtn = UIBarButtonItem(image: UIImage(named:"nav_btnback"), style: .plain, target: self, action: #selector(dismissSelf))
        navigationItem.leftBarButtonItem = backBarBtn
        oldNavDelegate = navigationController?.interactivePopGestureRecognizer?.delegate
        navigationController?.interactivePopGestureRecognizer?.delegate = self
//        navigationController?.interactivePopGestureRecognizer?.delegate = oldNavDelegate
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.interactivePopGestureRecognizer?.delegate = oldNavDelegate
    }
    
    func editBtnClick() {
        title = "修改项目"
        mode! = .edit
    }
    
    func saveBtnClick(modle: ModifyProjectModle) {
        
        let alert = SimpleSelfAlertViewController(title: nil, message: "是否保存该项目", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "保存", style: .default, handler: { (action) in
            self.saveProject(modle: modle)
        }))
        self.present(alert, animated: true, completion: nil)
    }
    
    func saveProject(modle: ModifyProjectModle){
        switch mode! {
        case .edit:
            var i = 0
            for index in testProjectID{
                if index.0 == modle.projectID{
                    testProjectID[i].1 = modle.projectName.0
                    testProjectModle[i]["PJName"] = modle.projectName.0
                    testDetailModle[i] = modle.projectDetail
                }
                i+=1
            }
        case .add:
            addProject(project: modle)
//            let id = (testProjectID.last?.0)!+1
//            testProjectID.append((id, modle.projectName.0))
//            testDetailModle.append(modle.projectDetail)
//            testProjectModle.append(["PJID": id,"PJName":modle.projectName.0,"PJMembers":[modle.projectDetail[0][2].2],"PJTime":modle.projectDetail[0][0].2+"-"+modle.projectDetail[0][1].2,"PJState":0])
        default:
            break
        }
        dismissSelf()
    }
    
    func addProject(project:ModifyProjectModle){
        var content = [[[String:String]]]()
        for detail in project.projectDetail{
            var cell=[[String:String]]();
            for desc in detail{
                cell.append(["tf_key":desc.1, "tf_value":desc.2, "tf_type":"defualt"])
            }
            content.append(cell)
        }
        print(content)
        let parameters = [
            "req":[
                "tp_name":project.projectName.0,
                "tp_genDate":"2017-01-01",
                "content": content
            ]
        ]
        SVProgressHUD.show(withStatus: "上传中")
        Alamofire.request(APIURL+"api/projects/create", method: .post, parameters: parameters, encoding: JSONEncoding.default).response { (response) in
            guard let data = HasCommonNetWorkError(response: response) else{
                SVProgressHUD.showError(withStatus: "上传失败")
                return
            }
            let json = JSON(data)

            if json["code"].int == 0 {
                SVProgressHUD.dismiss()
            }else{
                SVProgressHUD.showError(withStatus: "上传失败")
            }
        }

    }
    
    func dismissSelf(){
        navigationController?.popViewController(animated: true)
    }
}
